package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;

public class BibliotecaApp {

    private PrintStream printStream;
    private BufferedReader bufferedReader;
    private Library library;
    private Menu menu;
    private UserInputReader userInputReader;

    public BibliotecaApp(PrintStream printstream, BufferedReader bufferedreader, Library library, Menu menu, UserInputReader userInputReader) {
        this.printStream = printstream;
        this.bufferedReader = bufferedreader;
        this.library = library;
        this.menu = menu;
        this.userInputReader = userInputReader;
    }

    public void startApp() throws IOException {
        printStream.println("Welcome!");
        menu.printMenuOptions();
        String userInput = userInputReader.read();
        controlMenuInputLoop(userInput);
    }

    public static void main(String[] args) throws IOException {
        Library library = new Library();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        Menu menu = new Menu(library, reader, System.out);
        BibliotecaApp bibliotecaApp = new BibliotecaApp(System.out, reader, library, menu, new UserInputReader());
        bibliotecaApp.startApp();
    }

    public void checkIfValidMenuOption(String optionInput) {
       menu.checkMenuOption(optionInput);
    }

    private String getUserInput() throws IOException {
        return bufferedReader.readLine();
    }

    public void tryUserReservation() throws IOException {
        String bookToReserve = getUserInput();
        if (library.checkBookIsInLibrary(bookToReserve)) {
            if (library.checkBookReservation(bookToReserve)) {
                printStream.println("Book is reserved");
            } else {
                printStream.println("Thank You! Enjoy the book.");
                library.reserveBook(System.out, bookToReserve);
            }
        } else {
            printStream.println("Sorry, we don't have that book yet.");
        }
    }

    public void controlMenuInputLoop(String userInput) throws IOException {
        menu.respondToUserInput(userInput);
        menu.printMenuOptions();

    }
}
